<template>
  <div>
    <div class="detail-info" style="margin-top: 50px">
      <div class="form-item">
        <h4>基本信息</h4>
        <el-form :model="basicInfo" :rules="rules" ref="basicInfo" class="demo-ruleForm" label-width="180px">
          <el-row>
            <el-form-item label="所属分公司" label-width="180px" required>
              <el-select v-if="!brachDisabled" v-model="basicInfo.branchId" :disabled="brachDisabled"
              @change="getDeptList" @visible-change="visibleChange" style="width:200px" placeholder="分公司">
                <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
              </el-select>
              <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="所属部门" label-width="180px" prop="departmentId" required>
              <el-select v-if="!brachDisabled" v-model="basicInfo.departmentId" :disabled="brachDisabled" placeholder="所属部门" style="width:195px">
                <el-option v-for="(item, index) in this.deptList" :value="item.org_id" :label="item.org_name" :key="index"></el-option>
              </el-select>
              <el-input v-if="brachDisabled" v-model="this.showDept" disabled style="width:195px"></el-input>
            </el-form-item>
            <el-form-item label="客资类型" prop="customerType">
              <el-select v-model="basicInfo.customerType" style="width:220px" :loading="customerTypeLoading" placeholder="客资类型">
                <!-- <el-option value="1" label="普通超市"></el-option> -->
                <el-option v-for="(item, index) in customerTypeList"
                :key="index"
                :label="item.name"
                :value="item.id.toString()"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="促销费用" prop="salesCosts">
                <!-- <el-input v-model="basicInfo.salesCosts" style="width:210px"></el-input> -->
              <el-select v-model="basicInfo.salesCosts" @change="handleChangeSalesCosts" :loading="saleCostLoading" placeholder="请选择促销费用" style="width:220px">
                <el-option v-for="(item, index) in salesCostsList" :key="index" :label="item.promotionName" :value="item.id.toString()" ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="this.selectSalesCosts.type === 2 || this.selectSalesCosts.type === ''"
            label="供应商占比" prop="providerRatio">
              <el-input v-model="basicInfo.providerRatio" style="width:200px"></el-input>
              <span>%</span>
            </el-form-item>
            <el-form-item label="批次名称" prop="batchName">
              <el-input v-model="basicInfo.batchName" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="活动起止时间" prop="startStopTime">
              <el-date-picker :editable="false" v-model="basicInfo.startStopTime" type="daterange" value-format="yyyy-MM-dd"
              style="width:220px" @change="daterangeFormat" placeholder="批次有效期"
              :picker-options="pickerExpirationDate"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="领取方式" required >
              <el-radio-group v-model="basicInfo.doAction">
                <el-radio label="1">每日一次</el-radio>
                <el-radio label="2">一次性</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <!-- <el-form-item label="获取邮箱" required>
            <el-input v-model="basicInfo.hqemail" style="width:200px"></el-input>
          </el-form-item> -->
        </el-form>
			</div>
		</div>
    <div class="detail-info" style="margin-top: 50px">
      <div class="form-item">
        <h4>优惠券信息</h4>
        <el-button type="primary" :disabled="choseCodeDisabled" @click="handleChooseCode">选择优惠券</el-button>
        <el-table :data="redeemCodeDetails" border style="margin-top:20px;width: 100%">
          <el-table-column label="优惠券ID" prop="ticketId" align="center" width="80"></el-table-column>
          <el-table-column label="优惠券名称" prop="ticketName" align="center" width="100"></el-table-column>
          <el-table-column label="类型" align="center" width="100">
            <template scope="scope">
              <span v-if="scope.row.ticketType === '1'">现金券</span>
              <span v-if="scope.row.ticketType === '2'">满减券</span>
              <span v-if="scope.row.ticketType === '3'">实物券</span>
              <span v-if="scope.row.ticketType === '4'">品牌现金券</span>
              <span v-if="scope.row.ticketType === '6'">品类券</span>
            </template>
          </el-table-column>
          <el-table-column label="面值" prop="ticketMoney" align="center" width="60"></el-table-column>
          <el-table-column label="满多少元可用" prop="fullUse" align="center" width="95"></el-table-column>
          <el-table-column label="满多少件可用" prop="numLimit" align="center" width="95"></el-table-column>
          <el-table-column label="有效期类型" align="center" width="120">
            <template scope="scope">
              <el-select v-model="scope.row.expiryDateType" placeholder="有效期类型" @change="changeExpirationType($event, scope.row)">
                <el-option value="1" label="时间段"></el-option>
                <el-option value="2" label="截止时间"></el-option>
                <!-- <el-option v-if="selectSalesCosts.type === 1" value="3" label="天数"></el-option> 华九龄-->
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" min-width="245">
            <template scope="scope">
              <el-date-picker :editable="false" :clearable="false"
                v-show="scope.row.expiryDateType==='1'" v-model="scope.row.startTime"
                @change="valueToTable(scope.row, 'startTime', $event, scope.$index)"
                style="width:47%" placeholder="开始时间"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd">
              </el-date-picker>
              <el-date-picker :editable="false" :clearable="false"
                v-show="scope.row.expiryDateType==='1' || scope.row.expiryDateType==='2'"
                v-model="scope.row.endTime"
                @change="valueToTable(scope.row, 'endTime', $event, scope.$index)"
                style="width:47%" placeholder="结束时间"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd">
              </el-date-picker>
              <el-input v-show="scope.row.expiryDateType === '3'"
              v-model="scope.row.days" @blur="valueToTable(scope.row, 'days', $event, scope.$index)"
              style="width:45%" placeholder="请输入天数"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="生成总数" align="center" width="85">
            <template scope="scope">
              <el-input v-model="scope.row.total" @blur="valueToTable(scope.row, 'total', $event, scope.$index)" placeholder="生成总数"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="每人/数量" align="center" width="85">
            <template scope="scope">
              <el-input v-model="scope.row.ticketTimes" @blur="valueToTable(scope.row, 'ticketTimes', $event, scope.$index)" placeholder="每人/数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="建券人" prop="ticketUser" align="center" width="65"></el-table-column>
          <el-table-column label="操作" align="center" width="55">
            <template scope="scope">
              <el-button type="text" size="small" @click="deleteCoupon('优惠券', redeemCodeDetails, chooseCouponTableList, scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="选择优惠券" :visible.sync="couponDialog">
          <el-row style="margin-top:20px">
            <el-form :model="chooseCouponInfo">
              <el-col :span="6" style="margin-right:10px">
                <el-form-item label="券类型">
                  <el-select v-model="chooseCouponInfo.ticketType" placeholder="请选择券类型" style="width:130px">
                    <el-option v-for="(item, index) in ticketTypeGroup"
                    :key="index"
                    :value="item.ticketType.toString()"
                    :label="item.tname"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7" style="margin-right:10px">
                <el-form-item label="优惠券名称">
                  <el-input v-model="chooseCouponInfo.tname" placeholder="优惠券名称" style="width:130px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="7" style="margin-right:10px">
                <el-form-item label="优惠券ID">
                  <el-input v-model="chooseCouponInfo.id" placeholder="优惠券ID" style="width:130px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3" >
                <el-button type="primary" style="float:right" @click="searchCoupon('优惠券', chooseCouponTableList, redeemCodeDetails)">搜索</el-button>
              </el-col>
              <el-table :data="chooseCouponTableList" border v-loading="searchLoading">
                <el-table-column prop="ticketId" label="优惠券ID" align="center"></el-table-column>
                <el-table-column prop="ticketName" label="优惠券名称" align="center"></el-table-column>
                <el-table-column label="类型" align="center">
                  <template scope="scope">
                    <span v-if="scope.row.ticketType === '1'">现金券</span>
                    <span v-if="scope.row.ticketType === '2'">满减券</span>
                    <span v-if="scope.row.ticketType === '3'">实物券</span>
                    <span v-if="scope.row.ticketType === '4'">品牌现金券</span>
                    <span v-if="scope.row.ticketType === '6'">品类券</span>
                  </template>
                </el-table-column>
                <el-table-column prop="ticketMoney" label="面值" align="center"></el-table-column>
                <el-table-column prop="fullUse" label="满多少元可用" align="center"></el-table-column>
                <el-table-column prop="numLimit" label="满多少件可用" align="center" width="100"></el-table-column>
                <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template scope="scope">
                    <el-button v-if="scope.row.operation === 0" @click="addCode(scope.row, chooseCouponTableList[scope.$index])" type="text">添加</el-button>
                    <el-button v-if="scope.row.operation === 1" @click="recallCode(scope.row)" type="text">撤回</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                @current-change="handleCurrentChange"
                :page-size="Number(chooseCouponInfo.pageSize)"
                layout="total, prev, pager, next"
                :total="Number(chooseCouponInfo.total)"
                style="padding-top:10px;text-align: right;">
              </el-pagination>
            </el-form>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="couponDialogTrue">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="detail-info">
      <div class="form-item" style="margin-bottom:0">
        <h4>系统通知</h4>
        <el-row>
          <el-input style="width:400px" v-model="basicInfo.messageTitle" placeholder="请输入标题"></el-input>
        </el-row>
        <el-row>
          <el-input style="width:400px" v-model="basicInfo.messageDetails" type="textarea" placeholder="请输入内容"></el-input>
        </el-row>
      </div>
    </div>
    <div class="detail-info">
      <div class="form-item" style="margin-bottom:0">
        <h4>备注</h4>
        <el-input style="width:400px" type="textarea" placeholder="请输入备注" v-model="basicInfo.remark"></el-input>
      </div>
    </div>
    <div style="margin: 20px auto 20px;width:20%">
      <el-button @click="onSubmit(2, 'basicInfo')" type="success">提交</el-button>
      <el-button @click="onSubmit(1, 'basicInfo')" type="warning">暂存</el-button>
      <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
    </div>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../config/settings.js'
  import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  import moment from 'moment'
  export default {
    mixins: [mixins],
    data () {
      var self = this
//      var nameTest = (rule, value, callback) => { // 批次名称验证
//        if (!value) {
//          return callback(new Error('请输入批次名称'))
//        } else {
//          if (value.length > 16) {
//            callback(new Error('您输入的名称过长!'))
//          } else {
//            callback()
//          }
//        }
//      }
      var checkGysproportion = (rule, value, callback) => { // 验证供应商占比
        var text = rule.field === 'providerRatio' ? '供应商占比' : '订单满足金额'
        if (!value) {
          return callback(new Error(text + '不能为空'))
        } else {
          var reg = /^[0-9]\d*$/
          if (reg.test(value)) {
            value = value.toString()
            if (value.indexOf(0) === 0 && value.length > 1) {
              callback(new Error('不能以0开头'))
            } else {
              callback()
            }
          } else {
            callback(new Error('供应商占比必须正整数'))
          }
        }
      }
      return {
        pickerExpirationDate: { // 截止日期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() < new Date(self.selectSalesCosts.stime).getTime() || time.getTime() > new Date(self.selectSalesCosts.etime).getTime()
          }
        }, // 禁用时间段
        basicInfo: {
          branchId: '',
          departmentId: '',
          salesCosts: '', // 促销费用
          providerRatio: '', // 供应商补差占比
          batchName: '', // 批次名称
          doAction: '1', // 领取方式
          customerType: '1', // 客资类型
          // customerLevel: '', // 客户等级
          startStopTime: '', // 活动起止时间
          messageTitle: '', // 标题
          messageDetails: '', // 内容
          remark: '', // 备注
          startTime: '', // 活动开始时间
          endTime: '' // 活动结束时间
          // fileName: '' // 上传文件名称
        },
        // pageLoading: false,
        customerTypeList: [],
        customerTypeLoading: true,
        showBranchName: '', // 页面展示的公司名称
        showDeptName: '', // 页面展示的部门名称
        saleCostLoading: true, // 促销费用loading
        fileId: '', // 上传回来的id
        fileList: [],
        url: '',  // 上传路径
        uploadLoading: false, // 上传加载
        primaryDisabled: false, // 上传按钮
        choseCodeDisabled: false, // 选择优惠券按钮
        couponValid: false, // 验证优惠券
        searchLoading: false, // 查询优惠券loading
        salesCostsList: [], // 促销费用数组
        selectSalesCosts: {}, // 选中的促销费用
        redeemCodeDetails: [], // 优惠券数组
        ticketTypeGroup: [], // 优惠券类型数组
        validityType: '2', // 有效期类型
        validity: '', // 有效期
        creatTotal: '', // 生成总数
        tableTime: '',
        tableTimeRange: '',
        remark: '', // 备注
        chooseCouponTableList: [],
        couponDialog: false,
        chooseCouponInfo: { // 选择优惠券条件
          id: '', // 优惠券id
          ticketType: '4', // 优惠券类型
          tname: '', // 优惠券名称
          page: '1',
          pageSize: '20',
          total: 0
        },
        sendDetailPageSize: 10,
        sendDetailPage: 1,
        sendDetailDialog: false, // 发送明细
        sendDetail: [], // 发放明细
        sendDetailCheck: [], // 查看发放明细
        sendDetailType: 1,
        total: '',
        isCreateOrUpdate: '',
        text: '',
        menuId: '',
        // subDisabled: false,
        rules: {
          departmentId: [ // 促销费用
            {required: true, type: 'number', message: '请选择所属部门', trigger: 'change'}
          ],
          salesCosts: [ // 促销费用
            {required: true, message: '请选择促销费用', trigger: 'change'}
          ],
          customerType: [ // 客资类型
            {required: true, message: '请选择客资类型', trigger: 'change'}
          ],
          providerRatio: [ // 供应商占比
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          orderFullMoney: [ // 订单满足金额
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          batchName: [ // 批次名称
            {required: true, message: '请输入批次名称', trigger: 'blur'},
            { min: 0, max: 16, message: '长度不能超过16个字符', trigger: 'blur' }
          ],
          startStopTime: [ // 活动时间
            {type: 'array', required: true, message: '请选择活动起止日期', trigger: 'change'}
          ]
        },
        showBranch: '',
        showDept: '',
        newBranchId: '',
        createBranchId: '',
        brachDisabled: false,
        deptList: [],
        visible: false
      }
    },
    methods: {
      getDeptList (val) { // 获取部门
        console.log(this.visible)
        this.searchSalesCosts()
        if (this.visible === true) {
          console.log('aaa')
          this.basicInfo.departmentId = ''
          this.basicInfo.salesCosts = ''
        }
        var _data = {}
        var self = this
        setTimeout(() => {
          console.log(self.branchList)
          self.branchList.forEach(element => {
            if (val === element.branch_Id) {
              console.log(val === element.branch_Id)
              _data.orgId = element.org_id
              self.newBranchId = element.org_id
            }
          })
          console.log(_data)
          if (JSON.stringify(_data) === '{}') {
            return
          } else {
            getInfo.department(_data, (res) => {
              console.log(res)
              if (res.message === 'ok') {
                if (val === 1) {
                  self.deptList = []
                  res.content.forEach(element => {
                    if (element.org_name.indexOf('公司') === -1) {
                      self.deptList.push(element)
                    }
                  })
                  self.matchDept()
                } else {
                  self.deptList = res.content
                  self.matchDept()
                }
              } else {
                self.message(res.message, 'error')
              }
            })
          }
        }, 500)
      },
      matchDept () { // 匹配 当前登录人的部门与部门列表
        console.log(this.deptList)
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          console.log(Number(this.basicInfo.departmentId) === Number(element.org_id))
          console.log(Number(this.basicInfo.departmentId), Number(element.org_id))
          if (Number(this.basicInfo.departmentId) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.basicInfo.departmentId = ''
            }
          }
        }
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchSalesCosts () { // 查询促销费用
        var _data = {
          branchId: this.basicInfo.branchId,
          activityType: '-1'
        }
        activity.cxfy.allList(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.salesCostsList = res.content
            this.saleCostLoading = false
            // this.pageLoading = false
            // if (id) {
            //   this.searchDetail(id)
            // }
          }
        })
      },
      handleChangeSalesCosts (val) { // 选择促销费用
        for (var index = 0; index < this.salesCostsList.length; index++) {
          var element = this.salesCostsList[index]
          if (element.id === Number(val)) {
            if (element.promotionType === 1) {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: '',
                etime: ''
              }
            } else {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: this.timeDeltSecond(element.promotionBeginTime),
                etime: this.timeDeltSecond(element.promotionEndTime)
              }
            }
          }
        }
      },
      handleChooseCode () { // 选择优惠券按钮
        this.couponDialog = true
        this.searchCodeType()
      },
      searchCodeType () { // 查询券类型
        var _data = ''
        getInfo.couponType(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            // this.ticketTypeGroup = res.content
            for (var index = 0; index < res.content.length; index++) {
              var element = res.content[index]
              if (element.tname === '品牌现金券') {
                this.ticketTypeGroup.push(res.content[index])
              }
            }
            // console.log(res.content)
          }
        })
      },
      searchCoupon (text, arr1, arr2) { // 查询优惠券
        // console.log('查询优惠券')
        this.searchLoading = true
        var _dataCode = this.chooseCouponInfo
        _dataCode.branchId = this.basicInfo.branchId
        _dataCode.departmentId = this.basicInfo.departmentId
        _dataCode.bid = this.newBranchId
        // delete _dataCode.total
        console.log(_dataCode)
        getInfo.couponList(_dataCode, (res) => {
          if (res.message === 'ok') {
            console.log(res)
            this.searchLoading = false
            if (res.content.content !== null) {
              this.chooseCouponTableList = []
              for (var k = 0; k < res.content.content.length; k++) {
                var eleCode = res.content.content[k]
                this.chooseCouponTableList.push({
                  'ticketId': eleCode.id,
                  'ticketName': eleCode.tname,
                  'ticketType': this.chooseCouponInfo.ticketType,
                  'ticketMoney': eleCode.tcost !== null ? eleCode.tcost : '',
                  'fullUse': eleCode.fulluse !== null ? eleCode.fulluse : '',
                  'numLimit': eleCode.numLimit !== null ? eleCode.numLimit : '', // 满多少件可用
                  'remark': eleCode.remark,
                  'operation': 0,
                  'phpTicketId': eleCode.phpId
                })
                console.log('elecode')
                console.log(eleCode)
              }
              this.chooseCouponInfo.total = res.content.count
              this.chooseCouponInfo.page = res.content.page
              this.matchOperation(text, this.chooseCouponTableList, this.redeemCodeDetails)
            } else {
              this.chooseCouponTableList = []
            }
          }
        })
      },
      matchOperation () { // 查询时 匹配优惠券数组 和 已选则优惠券数组 显示 添加或撤回
        console.log(this.chooseCouponTableList)
        console.log(this.redeemCodeDetails)
        for (var i = 0; i < this.chooseCouponTableList.length; i++) {
          var allEle = this.chooseCouponTableList[i]
          if (this.redeemCodeDetails.length === 0) {
            this.chooseCouponTableList[i].operation = 0
          } else {
            for (var k = 0; k < this.redeemCodeDetails.length; k++) {
              var selectEle = this.redeemCodeDetails[k]
              if (Number(allEle.ticketId) === Number(selectEle.ticketId) && Number(allEle.ticketType) === Number(selectEle.ticketType)) {
                console.log('aaaa')
                this.chooseCouponTableList[i].operation = 1
              }
            }
          }
        }
      },
      addCode (row, data) { // 添加优惠券
        if (this.redeemCodeDetails.length >= 1) {
          this.message('添加失败！只能添加一条优惠券信息', 'error')
        } else {
          var newRow = {
            ticketTimes: '', // 每人/数量
            total: '', // 生成总数
            startTime: '', // 开始时间
            ticketUser: this.userName, // 建券人
            days: '', // 天数
            endTime: '', // 结束时间
            expiryDateType: '1', // 有效期类型
            ticketId: row.ticketId, // 优惠券id
            ticketType: row.ticketType, // 优惠券类型
            fullUse: row.fullUse, // 满多少可用
            numLimit: row.numLimit,
            ticketName: row.ticketName, // 优惠券名称
            ticketMoney: row.ticketMoney, // 面值
            validity: '',
            phpTicketId: row.phpTicketId,
            valida: false // 验证
          }
          this.redeemCodeDetails.push(newRow)
          data.operation = 1
        }
        this.resetChoseCode()
      },
      recallCode (row) { // 撤回
        console.log(arguments)
        for (var i = 0; i < this.redeemCodeDetails.length; i++) {
          var element = this.redeemCodeDetails[i]
          if (Number(element.ticketId) === Number(row.ticketId) && Number(element.ticketType) === Number(row.ticketType)) {
            this.redeemCodeDetails.splice(i, 1)
          }
        }
        row.operation = 0
        this.resetChoseCode()
      },
      resetChoseCode () { // 重置选择优惠券
        if (this.redeemCodeDetails.length === 0) {
          this.choseCodeDisabled = false
        } else if (this.redeemCodeDetails.length === 1) {
          this.choseCodeDisabled = true
        }
      },
      handleCurrentChange (val) { // 分页
        this.chooseCouponInfo.page = val
        this.searchCoupon('优惠券', this.chooseCouponTableList, this.redeemCodeDetails)
      },
      couponDialogTrue () { // 选择优惠券弹框确认按钮
        this.couponDialog = false
      },
      changeExpirationType (val, row, index) {
        // row.startTime = ''
        // row.endTime = ''
        // row.days = ''
      },
      valueToTable (row, name, val, index) { // 有效期类型赋值
        if (val && val !== '') {
          if (row.expiryDateType === '1') {
            row[name] = val
            // console.log(new Date(row.startTime))
            // console.log(new Date(row.endTime))
            if (row.startTime !== '' && row.endTime !== '') {
              if (new Date(row.startTime) <= new Date(row.endTime)) {
              } else {
                console.log(row)
                this.message('结束时间不能小于开始时间', 'error')
                row[name] = ''
              }
            }
          } else if (row.expiryDateType === '2') {
            row[name] = val
          } else if (row.expiryDateType === '3') {
            row[name] = val
          }
          if (name === 'days' || name === 'ticketTimes' || name === 'total') {
            // var text = name === 'days' ? '天数' : '每人/数量'
            var text = ''
            if (name === 'days') { text = '天数' }
            if (name === 'ticketTimes') { text = '每人/数量' }
            if (name === 'total') { text = '发放数量' }
            val = val.srcElement.value
            var re = /^[1-9]\d*$/
            if (re.test(val)) {
              row[name] = val
            } else {
              this.message('第' + (index + 1) + '行' + text + '格式错误，请输入正整数！', 'error')
              row[name] = ''
            }
          }
        }
      },
      deleteCoupon (text, arr, arr2, index, row) { // 删除优惠券
        // console.log(index)
        this.$confirm('您确定要删除该条优惠券信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.redeemCodeDetails.splice(index, 1)
          this.message('删除成功', 'success')
          this.resetChoseCode()
          for (var i = 0; i < arr2.length; i++) {
            var element1 = arr2[i]
            if (Number(element1.ticketId) === Number(row.ticketId) && Number(element1.ticketType) === Number(row.ticketType)) {
              element1.operation = 0
            }
          }
        }).catch(() => {
        })
      },
      searchDetail (row) { // 查询详情
        activity.yhqhd.lqzx.detail({id: row.id}, (res) => {
          // console.log(res)
          if (res.message === 'ok') {
            console.log(res.content)
            // this.pageLoading = false
            this.creatRedeemCodeDetail(res.content)
            this.basicInfo.branchId = res.content.branchId // 创建时公司是返回的公司id
            this.showBranch = res.content.branchName // 创建时公司是返回的公司名称
            this.basicInfo.departmentId = res.content.departmentId // 创建时公司是返回的部门id
            this.showDept = res.content.departName // 创建时公司是返回的部门名称
            this.createBranchId = this.branchOrgId // 创建时创建人新公司ID
            this.searchSalesCosts()
            this.$store.dispatch('pageLoading', false)
          } else {
            this.$store.dispatch('pageLoading', false)
            this.message('查看详情失败', 'error')
          }
        })
      },
      creatRedeemCodeDetail (res) { // 详情回填
        this.basicInfo.salesCosts = res.salesCosts.toString() // 促销费用
        this.basicInfo.expirationDate = res.expirationDate // 兑换截止日期
        this.basicInfo.providerRatio = res.providerRatio // 供应商补差占比
        this.basicInfo.batchName = res.batchName // 批次名称
        // this.basicInfo.hqemail = res.hqemail // 邮箱
        this.basicInfo.remark = res.remark // 备注
        this.basicInfo.messageTitle = res.messageTitle // 标题
        this.basicInfo.messageDetails = res.messageDetails // 内容
        this.basicInfo.doAction = res.doAction.toString() //  领取方式
        this.basicInfo.startStopTime = [this.timeDeltSecond(res.startTime), this.timeDeltSecond(res.endTime)] // 发送时间
        // console.log(res.startTime)
        this.redeemCodeDetails = res.tickets
        console.log(this.redeemCodeDetails)
        // if (this.basicInfo.doAction === '1') {
        for (var index = 0; index < res.tickets.length; index++) {
          var element = res.tickets[index]
          this.redeemCodeDetails[index].expiryDateType = element.expiryDateType.toString()
          this.redeemCodeDetails[index].ticketType = element.ticketType.toString()
          if (element.expiryDateType === '1') {
            this.redeemCodeDetails[index].startTime = this.timeDeltSecond(element.startTime)
            this.redeemCodeDetails[index].endTime = this.timeDeltSecond(element.endTime)
          }
          if (element.expiryDateType === '2') {
            this.redeemCodeDetails[index].endTime = this.timeDeltSecond(element.endTime)
          }
          if (element.expiryDateType === '3') {
            this.redeemCodeDetails[index].days = element.days
          }
        }
        // }
        // console.log(this.redeemCodeDetails)
      },
      creatData (buttonType) { // 创建 提交 _data
        this.basicInfo.doAction = Number(this.basicInfo.doAction)
        this.basicInfo.providerRatio = this.selectSalesCosts.type === 2 ? this.basicInfo.providerRatio : 0
        console.log(this.basicInfo)
        var dataInfo = {
          branchId: this.basicInfo.branchId, // 旧分公司id
          departmentId: this.basicInfo.departmentId, // 部门id
          newBranchId: this.newBranchId, // 新公司id
          createBranchId: this.branchOrgId, // 创建人新公司ID
          editBy: this.userName, // 编辑人 当前用户
          createBy: this.userName, // 创建人 当前用户
          userId: this.userId,
          batchId: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '', // 批次id
          id: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '', // 批次id
          buttonType: buttonType, // 创建或者保存
          gwId: this.roleId, // 岗位ID
          uorId: this.uorId // 用户id
        }
        // console.log(this.redeemCodeDetails)
        var _data = {}
        _data = Object.assign(this.basicInfo, dataInfo)
        // if (this.basicInfo.doAction === '1') {
        var tickets = []
        for (var index = 0; index < this.redeemCodeDetails.length; index++) {
          var element = this.redeemCodeDetails[index]
          var redeemCodeDetailObj = {}
          redeemCodeDetailObj.ticketTimes = element.ticketTimes // 每人/数量
          redeemCodeDetailObj.total = element.total // 发放数量
          redeemCodeDetailObj.ticketId = element.ticketId // 券id
          redeemCodeDetailObj.expiryDateType = Number(element.expiryDateType) // 有效期类型
          redeemCodeDetailObj.ticketType = element.ticketType // 优惠券类型
          redeemCodeDetailObj.ticketUser = element.ticketUser // 建券人
          redeemCodeDetailObj.phpTicketId = element.phpTicketId //
          if (Number(element.expiryDateType) === 1) {
            redeemCodeDetailObj.startTime = element.startTime
            redeemCodeDetailObj.endTime = element.endTime
            redeemCodeDetailObj.days = ''
          }
          if (Number(element.expiryDateType) === 2) {
            redeemCodeDetailObj.endTime = element.endTime
            redeemCodeDetailObj.days = ''
            redeemCodeDetailObj.startTime = ''
          }
          if (Number(element.expiryDateType) === 3) {
            redeemCodeDetailObj.endTime = ''
            redeemCodeDetailObj.startTime = ''
            redeemCodeDetailObj.days = element.days
          }
          tickets.push(redeemCodeDetailObj)
        }
        _data.tickets = tickets
        // }
        return _data
      },
      onSubmit (buttonType, formName) { // 提交
        this.$refs[formName].validate((valid) => {
          this.formValidation()
          var self = this
          // console.log(this.couponValid)
          console.log(this.basicInfo)
          console.log(new Date(this.basicInfo.startTime))
          console.log(new Date(this.basicInfo.endTime))
          setTimeout(function () {
            if (valid && self.couponValid === true) {
              var _data = self.creatData(buttonType)
              console.log(_data)
              // self.subDisabled = true
              activity.yhqhd.lqzx[self.isCreateOrUpdate](_data, (res) => {
                console.log(res)
                if (res.message === 'ok') {
                  self.cancel(self.menuId)
                  self.message(self.text + '成功', 'success')
                  console.log(self.text)
                  self.$store.dispatch('lqzxState', self.$store.state.updateState.lqzxState + 1)
                  // self.subDisabled = false
                } else {
                  self.message(res.message, 'error')
                  // self.subDisabled = false
                }
              })
            } else {
              return false
            }
          }, 100)
        })
      },
      formValidation () { // 提交表单验证
        // console.log(this.redeemCodeDetails)
        if (this.redeemCodeDetails.length !== 0) {
          for (var index = 0; index < this.redeemCodeDetails.length; index++) {
            var element = this.redeemCodeDetails[index]
            if (Number(element.expiryDateType) === 1) {
              if ((element.startTime !== '' && element.endTime !== '') && element.total !== '' && element.ticketTimes !== '') {
                if (moment(element.startTime).valueOf() >= moment(this.basicInfo.startTime).valueOf()) {
                  this.couponValid = true
                } else {
                  this.message('活动开始时间小于等于优惠券开始时间', 'error')
                  this.basicInfo.startStopTime = ''
                  this.couponValid = false
                }
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
            if (Number(element.expiryDateType) === 2) {
              if (element.endTime !== '' && element.total !== '' && element.ticketTimes !== '') {
                if (moment(element.endTime).valueOf() > moment(this.basicInfo.startTime).valueOf()) {
                  this.couponValid = true
                } else {
                  this.message('活动开始时间小于优惠券结束时间', 'error')
                  this.basicInfo.startStopTime = ''
                  this.couponValid = false
                }
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
            if (Number(element.expiryDateType) === 3) {
              if (element.days !== '' && element.total !== '' && element.ticketTimes !== '') {
                this.couponValid = true
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
          }
        } else {
          this.couponValid = false
          this.message('优惠券不为空', 'error')
        }
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      daterangeFormat (t) { // 时间段格式化
        if (t) {
          this.basicInfo.startTime = t[0]
          this.basicInfo.endTime = t[1]
        } else {
          this.basicInfo.startStopTime = []
          this.basicInfo.startTime = ''
          this.basicInfo.endTime = ''
        }
      },
      timeFormat (d, n) { // 时间格式化
        if (d && d !== '') {
          if (n === 'single') {
            this.basicInfo.sendTime = d
          } else if (n === 'double') {
            return d.split(' - ')
          }
        }
      },
      timeDeltSecond (d) { // 时间去秒
        return d.split(' ')[0]
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    created () {
      this.url = 'http://' + apiHost.newCms + ':20000' + apiURL.timeingOn_upload
      console.log(this.$store.state.tab)
      this.menuId = this.$store.state.tab.menuId
      if (this.$store.state.tab.uid) {
        this.isCreateOrUpdate = 'update'
        this.text = '编辑'
        // this.pageLoading = true
        this.$store.dispatch('pageLoading', true)
        this.searchDetail(this.$store.state.tab.uid)
        // this.searchSalesCosts(this.$store.state.tab.uid) // 查询促销费用
        this.searchCustomerType()
        if (this.branchId === 1) {
          this.brachDisabled = false
        } else {
          this.brachDisabled = true
        }
      } else {
        this.isCreateOrUpdate = 'create'
        this.text = '新增'
        if (this.branchId === 1) {
          this.brachDisabled = false
          this.basicInfo.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          this.createBranchId = this.branchOrgId
        } else {
          this.brachDisabled = true
          this.showBranch = this.branchName
          this.showDept = this.deptName
          this.basicInfo.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          this.createBranchId = this.branchOrgId
          // this.formInline.branchId = this.branchId
        }
        this.searchSalesCosts() // 查询促销费用
        this.searchCustomerType()
        // this.showBranchName = this.branchName // 创建时公司是返回的公司名称
        // this.showDeptName = this.deptName
      }
      console.log(this.isCreateOrUpdate)
    },
    computed: mapState({
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      userId: function (state) {
        return state.user.info.user_id
      },
      roleId: function (state) {
        return state.user.info.roleid
      },
      uorId: function (state) {
        return state.user.info.uor_id
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      branchOrgId: function (state) {
        return state.user.info.branchOrgId
      },
      deptName: function (state) {
        return state.user.info.parOrgName
      },
      deptId: function (state) {
        return state.user.info.or_org_id
      }
    }),
    watch: {
      branchList (a, b) {
        this.getDeptList(this.basicInfo.branchId)
      }
    }
  }
</script>






